package com.basker.pisces.excel.poi;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.basker.pisces.excel.IWorkBook;
import com.basker.pisces.excel.IWorkbookFactory;
import com.basker.pisces.excel.enums.WorkbookType;
import com.basker.pisces.exception.ExceptionFactory;

public class POIWorkbookFactory implements IWorkbookFactory {

    @Override
    public IWorkBook create(WorkbookType type) {
        boolean xssf = type.equals(WorkbookType.XLSX);
        Workbook workbook = null;

        try {
            workbook = WorkbookFactory.create(xssf);
        } catch (IOException e) {
            throw ExceptionFactory.createRuntimeException(e);
        }

        return new POIWorkbook(workbook);
    }

    @Override
    public IWorkBook load(File file) {
        Workbook workbook = null;

        try {
            workbook = WorkbookFactory.create(file);
        } catch (EncryptedDocumentException | IOException e) {
            throw ExceptionFactory.createRuntimeException(e);
        }

        return new POIWorkbook(workbook);
    }

    @Override
    public IWorkBook load(InputStream inputStream) {
        Workbook workbook = null;

        try {
            workbook = WorkbookFactory.create(inputStream);
        } catch (EncryptedDocumentException | IOException e) {
            throw ExceptionFactory.createRuntimeException(e);
        }

        return new POIWorkbook(workbook);
    }

}
